package com.bcu.calculus.service.serviceImpl;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.sax.Excel07SaxReader;
import cn.hutool.poi.excel.sax.handler.RowHandler;
import com.bcu.calculus.entity.*;
import com.bcu.calculus.mapper.*;
import com.bcu.calculus.service.UserService;
import com.bcu.calculus.utils.StringToList;
import lombok.Data;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class UserServiceImpl implements UserService {
    private Logger logger= LoggerFactory.getLogger(getClass());

    @Resource
    private UserMapper userMapper;
    @Resource
    private BranchMapper branchMapper;
    @Resource
    private UserinfoMapper userinfoMapper;
    @Resource
    private FlistMapper flistMapper;
    @Resource
    private SlistMapper slistMapper;
    @Resource
    private TlistMapper tlistMapper;

    @Override
    public Message<?> addUser(User user) {
        User u = userMapper.selectByPrimaryKey(user.getUserId());
        if (u == null)
        {
            logger.info("用户-----添加用户,userId为 "+user.getUserId());
            return userMapper.insert(user) > 0 ? Message.success("添加"+user.getUserId()+"用户成功") : Message.fail("添加失败");
        }
        else {
            logger.info("用户-----添加用户失败,userId存在,userId为 "+user.getUserId());
            return Message.fail("用户工号已经存在");
        }
    }

    @Override
    public Message<User> Login(String userId, String userPwd) {

        //需要增加type转型

        User user = userMapper.selectByPrimaryKey(userId);
        if (user == null){
            logger.info("用户-----尝试进行登录操作,但是登陆失败,用户不存在,userId为 "+userId);
            return Message.fail("用户不存在");
        }else{
            if (user.getUserPwd().equals(userPwd)){
                logger.info("用户-----登录成功userId为 "+userId);
                UserInfo userInfo = userinfoMapper.selectByPrimaryKey(user.getUserId());
                userInfo.setBranch(branchMapper.selectByPrimaryKey(userInfo.getUserBranch()));
                user.setUserinfo(userInfo);
                return Message.success(null).add(user);
            }else{
                logger.info("用户-----尝试进行登录操作,但是登陆失败,密码错误,userId为 "+userId);
                return Message.fail("账号密码错误");
            }
        }
    }

    @Override
    public Message<?> insertUserSelective(User user) {
        User u = userMapper.selectByPrimaryKey(user.getUserId());
        if (u == null)
        {
            logger.info("用户-----添加用户,userId为 "+user.getUserId());
            return userMapper.insertSelective(user) > 0 ? Message.success("添加"+user.getUserId()+"用户成功") : Message.fail("添加失败");
        }
        else {
            logger.info("用户-----尝试添加用户,但是添加失败,userId存在,userId为 "+user.getUserId());
            return Message.fail("用户工号已经存在");
        }
    }

    @Override
    public Message<?> delUser(String userId) {

        User user = userMapper.selectByPrimaryKey(userId);
        if (user == null)
        {
            logger.info("用户-----尝试删除用户,但是删除失败,userId不存在,userId为 "+userId);
            return Message.fail("用户不存在");
        }
        else {
            logger.info("用户-----删除用户,userId为 "+userId);
            return userMapper.deleteByPrimaryKey(userId) > 0 ? Message.success("删除"+userId+"用户成功") : Message.fail("删除失败");

        }
    }

    @Override
    public Message<UserNumber> findUserByPrimaryKey(String userId) {
        User user = userMapper.selectByPrimaryKey(userId);
        UserNumber userNumber = new UserNumber();
        userNumber.setUserId(user.getUserId());
        userNumber.setUserPwd(user.getUserPwd());
        userNumber.setUserType(StringToList.change(user.getUserType()));
        userNumber.setUserStatus(user.getUserStatus());
        System.out.printf(userNumber.toString());
        logger.info("用户-----通过关键字查询所有用户,userId为 "+userId);
        return Message.success(null).add(userNumber);
    }

    @Override
    public Message<User> findUserAndInfoByPrimaryKey(String userId) {
        logger.info("用户-----通过userId查找用户,userId为 "+userId);
        User user  = userMapper.findOneUserAndInfoByPrimaryKey(userId);
        UserInfo userInfo = userinfoMapper.selectByPrimaryKey(user.getUserId());
        userInfo.setBranch(branchMapper.selectByPrimaryKey(userInfo.getUserBranch()));
        user.setUserinfo(userInfo);
        return Message.success(null).add(user);
    }

    @Override
    public Message<List<User>> findAllUser() {
        logger.info("用户-----查询所有用户");
        return Message.success(null).add(userMapper.findAllUser());
    }

    @Override
    public Message<List<User>> findAllUserAndUserInfo() {
        logger.info("用户-----查找所有 用户 和 用户信息");
        List<User> userList =  userMapper.findAllUser();
        for (User user:userList) {
            UserInfo userInfo = userinfoMapper.selectByPrimaryKey(user.getUserId());
            userInfo.setBranch(branchMapper.selectByPrimaryKey(userInfo.getUserBranch()));
            user.setUserinfo(userInfo);
        }
        return Message.success(null).add(userList);
    }

    @Override
    public Message<?> updateUserByPrimaryKeySelective(User user) {
        User u = userMapper.selectByPrimaryKey(user.getUserId());
        if (user == null)
        {
            logger.info("用户-----尝试通过关键字修改用户信息,但是修改失败,userId不存在,userId为 "+user.getUserId());
            return Message.fail("用户不存在");
        }
        else {
            logger.info("用户-----修改用户信息,userId为 "+user.getUserId());
            return userMapper.updateByPrimaryKeySelective(user) > 0 ? Message.success("更新"+user.getUserId()+"用户成功") : Message.fail("更新失败");
        }
    }

    @Override
    public Message<?> updateUserByPrimaryKey(User user) {
        User u = userMapper.selectByPrimaryKey(user.getUserId());
        if (user == null)
        {
            logger.info("用户-----尝试通过关键字修改用户,但是修改失败,userId不存在,userId为 "+user.getUserId());
            return Message.fail("用户不存在");
        }
        else {
            logger.info("用户-----通过关键字修改用户信息,userId为 "+user.getUserId());
            return userMapper.updateByPrimaryKey(user) > 0 ? Message.success("更新"+user.getUserId()+"用户成功") : Message.fail("更新失败");
        }
    }

    @Override
    public Message<List<User>> getAllUserRankInBranch(Integer branch) {
        return Message.success(null).add(userMapper.findAllUserAndInfoOrderByScoreInBranch(branch));
    }

    @Override
    public Message<Integer> getOneUserRank(String userId) {
        int rank = 0;
        List<User> users = userMapper.findAllUserAndInfo();
        for (User u:users) {
            rank++;
            if (userId.equals(u.getUserId())){
                break;
            }
        }

        return Message.success(null).add(rank);
    }

    @Override
    public Message<Integer> getOneUserRankInBranch(String userId, Integer branch) {
        int rank = 0;
        List<User> users = userMapper.findAllUserAndInfoOrderByScoreInBranch(branch);
        for (User u:users) {
            rank++;
            if (userId.equals(u.getUserId())){
                break;
            }
        }

        return Message.success(null).add(rank);
    }

    @Override
    public Message getListByUserType(String userType) {


       /**
        * 新逻辑
        * 先确定需要的一级路由
        * 循环一级路由，以及路由包含的二级路由要满足，以及路由为user_type确定，上级路由为该一级路由，
        * */


        List<FlistH> list = new ArrayList<>();
        if(userType.equals("0")){
            List<Flist> flistList = flistMapper.selectAllFlist();

            for (Flist f:flistList) {
                FlistH flistH = new FlistH();
                flistH.setFlist(flistMapper.selectByPrimaryKey(f.getFlistId()));

                List<Slist> slists2 = slistMapper.getSlistByFlistId(f.getFlistId());
                List<SlistH> slistHS = new ArrayList<>();

                for (Slist slist:slists2) {
                    SlistH slistH = new SlistH();
                    slistH.setSlist(slist);
                    slistH.setTlist(tlistMapper.getTlistBySlistId(slist.getSlistId()));
                    slistHS.add(slistH);
                }
                flistH.setSlists(slistHS);
                list.add(flistH);
            }
        }else{

            //先确定需要的一级路由
            List<String> flistIds = slistMapper.getFlistIdByUserType(userType);
            //加入首页这一项(这种方式不靠谱，但没想出来靠谱的)
            flistIds.add("FL58");
            //System.out.println(flistIds.toString());
            List<String> slistIds = tlistMapper.getSlistIdByUserType(userType);
            for (String id:slistIds) {
                Slist s = slistMapper.selectByPrimaryKey(id);
                flistIds.add(s.getSlistFlistId());
                //System.out.println(s.getSlistFlistId());
            }
            //去除重复
            Set<String> set = new  HashSet<>();
            List<String> newList = new  ArrayList<>();
            set.addAll(flistIds);
            newList.addAll(set);
            //排序
            //重写排序方法
//            Collections.sort(newList, new Comparator() {
//                @Override
//                public int compare(Object o1, Object o2) {
//                    return new Double((String) o1).compareTo(new Double((String) o2));
//                }
//            });
            //System.out.print(newList.toString());


            //循环一级路由，以及路由包含的二级路由要满足，以及路由为user_type确定，上级路由为该一级路由
            for (String flistId:newList) {
                FlistH flistH = new FlistH();
                flistH.setFlist(flistMapper.selectByPrimaryKey(flistId));

                //user_type为b的由三级路由确定的二级路由的id

                List<Slist> slists1 = new ArrayList<>();
                for (String id:slistIds) {

                    //需要确定此二级路由属于该以及路由
                    Slist s = slistMapper.selectByPrimaryKey(id);
                    if (s.getSlistFlistId().equals(flistId)){
                        slists1.add(s);
                    }

                }

                List<Slist> slists2 = slistMapper.getSlistByuerTypeAndFlistId(userType,flistId);

                List<Slist> collect = Stream.of(slists1, slists2)
                        .flatMap(Collection::stream)
                        .distinct()
                        .collect(Collectors.toList());
                List<SlistH> slistHS = new ArrayList<>();
                for (Slist slist:collect) {
                    SlistH slistH = new SlistH();
                    slistH.setSlist(slist);
                    slistH.setTlist(tlistMapper.getTlistByuerTypeAndSlistId(userType,slist.getSlistId()));
                    slistHS.add(slistH);
                }
                flistH.setSlists(slistHS);
                list.add(flistH);
            }
        }

        Collections.sort(list,
                Comparator.comparing((Object o) -> ((FlistH) o).getFlist().getFlistPosition()));

        return Message.success(null).add(list);
    }

    @Override
    public Message uploadByExcel(InputStream inputStream) throws IOException {
        ExcelReader excelReader = ExcelUtil.getReader(inputStream, 0);
        List<List<Object>> read = excelReader.read(1, excelReader.getRowCount());
        List<HashMap<String,Object>> userList = new ArrayList<HashMap<String, Object>>();
        User user = new User();
        UserInfo userInfo = new UserInfo();
        int k=0;
        for (List<Object> objects : read) {
            HashMap<String,Object> u = new HashMap<>();
            u.put("name",objects.get(1));
            u.put("id",objects.get(2));
            // objects.get(0),读取某行第一列数据
            // objects.get(1),读取某行第二列数据
//            System.out.println(u.get("name"));
            String id =String.valueOf(u.get("id"));
            String username =String .valueOf(u.get(("name")));
            User a = userMapper.selectByPrimaryKey(id);
            UserInfo b = userinfoMapper.selectByPrimaryKey(id);

            /*
            关于user的
            如果在数据库中  查到  这个id，无事发生
            如果在数据库中 没查到  这个id，就会将这个人的id存入，密码初始化为000000，只有权限8
            */

            /*
            关于userInfo的
            如果在数据库中  查到  这个id，更新姓名
            如果在数据库中 没查到  这个id，就会将这个人的id存入，姓名存入，党小组默认为空
            */
            if(b!= null){
                userInfo.setUserName(username);
                userInfo.setUserId(id);
                userInfo.setUserBranch(7);
                userinfoMapper.updateByPrimaryKeySelective(userInfo);
                if(a==null){
                    user.setUserId(id);
                    user.setUserPwd("000000");
                    user.setUserType("8");
                    user.setUserStatus(1);
                    userMapper.insert(user);
                }
            }else{
                if(b==null){
                    userInfo.setUserId(id);
                    userInfo.setUserName(String.valueOf(u.get("name")));
                    userInfo.setUserBranch(7);
                    userinfoMapper.insert(userInfo);
                }
                if(a==null){
                    user.setUserId(id);
                    user.setUserPwd("000000");
                    user.setUserType("8");
                    user.setUserStatus(1);
                    userMapper.insert(user);
                }
            }



        }
        inputStream.close();
        return Message.success("上传成功");
    }

    @Data
    static class FlistH{
        private Flist flist;
        private List<SlistH> slists;


    }
    @Data
    static class SlistH{
        private Slist slist;
        private List<Tlist> tlist;
    }



}